import { ref, computed, watch, toRaw } from 'vue'
import { defineStore, storeToRefs } from 'pinia'
import { useConnectorStore } from '@/stores/connector'
import { utils } from 'ethers'

type Network = {
  name: string
  chainId: number
}

export const useAccountStore = defineStore('accountStore', () => {
  const balance = ref('0')
  const blockNumber = ref(0)
  const network = ref<Network>({
    name: '',
    chainId: 0,
  })
  const balanceFixed = computed(() => parseFloat(balance.value).toFixed(4))

  const connectorStore = useConnectorStore()
  // const { connect } = connectorStore
  const connect = toRaw(connectorStore.connect)
  const { account, chainId } = storeToRefs(connectorStore)

  watch(account, async (newVal: string) => {
    if (newVal != '' && connect.provider) {
      connect.provider.on('block', (block) => {
        blockNumber.value = block
      })
      try {
        const networkInfo = await connect.provider.detectNetwork()
        network.value.chainId = networkInfo.chainId
        network.value.name = networkInfo.name

        const accounts = await connect.provider.listAccounts()
        const balanceOf = await connect.provider.getBalance(accounts[0])
        balance.value = utils.formatEther(balanceOf).toString()
      } catch (error) {
        console.log('[ error ] >', error)
      }
    }
  })
  watch(chainId, async () => {
    if (!connect.provider) return
    try {
      const networkInfo = await connect.provider.detectNetwork()
      network.value.chainId = networkInfo.chainId
      network.value.name = networkInfo.name
    } catch (error) {
      console.log('[ error ] >', error)
    }
  })

  return { balance, balanceFixed, blockNumber, network }
})
